var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../common/common');
var DBConfig = require('../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql); 

// 复制原数据库中的商品和分类之间的关系
router.get('/jkyx/copy_goods_classify', function(req, res, next) {
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getGoods_classify,function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				// 处理商品
				var comments = results;
//				res.end(JSON.stringify({
//	     			msg: '数据库查询失败',
//	     			status:'102',
//	     			err: results
//	     		}));
//	     		return;
				var comments_len = comments.length;
				var values2 = '';
				for (var i = 0; i < comments_len; i ++) {
//id INT(11) NOT NULL AUTO_INCREMENT,
//level INT(10) NOT NULL COMMENT "分类级别",
//pid INT(10) NOT NULL COMMENT "二级分类",
//name VARCHAR(250) NOT NULL DEFAULT '' COMMENT "分类名字",
//descr VARCHAR(250) NOT NULL DEFAULT '' COMMENT "描述",
//logo VARCHAR(250) NOT NULL DEFAULT '' COMMENT "图标",
//sort VARCHAR(3) NOT NULL DEFAULT '' COMMENT "排序",
//status VARCHAR(1) NOT NULL DEFAULT '1' COMMENT "1:显示 2:不显示",
//create_time VARCHAR(20) NOT NULL DEFAULT '' COMMENT "时间戳",
					var level = comments[i].level;
					var pid = comments[i].pid;
					var name = comments[i].name;
					var desc = comments[i].desc;
					var logo = comments[i].logo || '';
					var sort = comments[i].sort;
					var status = comments[i].show_status;
					var create_time = '2017-11-30 11:25:22';
					
					var values = "'" + level + "'" + ',' 
		  	  			 + "'" + pid + "'" + ',' 
		  	  			 + "'" + name + "'" + ',' 
		  	  			 + "'" + desc + "'" + ',' 
		  	  			 + "'" + logo + "'" + ',' 
		  	  			 + "'" + sort + "'" + ',' 
		  	  			 + "'" + status + "'" + ',' 
		  	  			 + "'" + create_time + "'";
		  	        if (i == (comments_len - 1)) {
		  	        		values = '(' + values + ')';
		  	        }else{
		  	        		values = '(' + values + '),';
		  	        }
		  	        values2 = values2 + values;
				}
				var inserSql = 'insert into goods_classify (level,pid,name,descr,logo,sort,status,create_time) values ' + values2 + ';';
				var pool2 = mysql.createPool(DBConfig.mysql2);
				pool2.getConnection(function(err, connection) {
					connection.query(inserSql,function (err, results) {
						if (err){
						  	res.end(JSON.stringify({
				     			msg: '数据库查询失败',
				     			status:'102',
				     			err: err
				     		}));
						}else{
							res.end(JSON.stringify({
				     			msg: '操作成功',
				     			status:'100',
				     		}));	      
						}
					})
				})   
			}
		})
	})
});


module.exports = router;
